package com.jzy.hzit.service.impl;

import com.alibaba.fastjson.JSON;
import com.jzy.hzit.entity.LoginUser;
import com.jzy.hzit.service.TokenService;
import com.jzy.hzit.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
public class TokenServiceImpl implements TokenService {
	@Autowired
	private StringRedisTemplate redisTemplate;
	//1. 生成token
	@Override
	public Map<String, Object> createToken(LoginUser user) {
		//1.1 生成token加密的字符串
		Map<String, Object> climas = new HashMap<>();
		String uuid = UUID.randomUUID().toString().replace("-","");
		climas.put("userId",user.getUserId());
		climas.put("username",user.getUser().getUsername());
		climas.put("user_key",uuid);
		String token = JwtUtil.createToken(climas);

		//1.2 将生成的结果map返回给前端，前端存放在cookie中，以后每次请求的请求头都会携带一个token，这个token的名字叫：
		//Authorization，值以Bearer 开头，后面跟的就是token值
		Map<String,Object> resultMap = new HashMap<>();
		resultMap.put("token",token);

		//1.3 将登录用户存放到redis中
		// 1.3.1 redis的key
		String key = "login_tokens:" + uuid;
		// 1.3.2 redis的值就是登录用户
		redisTemplate.opsForValue().set(key, JSON.toJSONString(user),100, TimeUnit.DAYS);

		return resultMap;
	}
}
